package com.elong.businesstravel.modules.home.hotel.hotelpayment;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.android.support.jhf.edittextclear.EditTextClearView;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.RequestParams;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.AppJump;
import com.android.support.jhf.utils.ConfigManager;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.AlipayResult;
import com.elong.businesstravel.entitys.HotelDocs;
import com.elong.businesstravel.entitys.MemberManaged;
import com.elong.businesstravel.entitys.HotelPrice.GuaranteeRuleInfo;
import com.elong.businesstravel.entitys.HotelPrice.PrepayRuleInfo;
import com.elong.businesstravel.entitys.HotelPrice.RatePlanInfo;
import com.elong.businesstravel.modules.member.WebViewActivity;
import com.elong.businesstravel.modules.orders.OrdersActivity;
import com.elong.businesstravel.protocol.login.MemberGetManagedRequest;
import com.elong.businesstravel.protocol.login.MemberGetManagedResponse;
import com.elong.businesstravel.protocol.order.CreateOrderRequest;
import com.elong.businesstravel.protocol.order.CreateOrderResponse;
import com.umeng.analytics.MobclickAgent;

/**
 * 支付方式
 * 
 * @author lenovo
 * 
 */
public class PaymentActivity extends BaseActivity {
	/** 支付类型 4218支付宝网页 */
	private static final String PAYMENTMOTHD_WEB = "4218";
	/** 4215支付宝客户端 */
	private static final String PAYMENTMOTHD_APP = "4215";

	private EditTextClearView mInvoiceTitleEditTextClearView;
	private TextView mInvoiceTypeTextView;
	private TextView mBalanceFlagTextView;
	private EditTextClearView mNameEditTextClearView;
	private EditTextClearView mPhoneEditTextClearView;
	private EditTextClearView mAddressEditTextClearView;
	private ViewGroup mInvoiceLayout;
	private TextView mPaypalRightTextView;
	private TextView mCreditCardTextView;
	private TextView mBalanceTextView;
	private TextView mRedPurseTextView;
	private TextView mBalanceRightTextView;
	private TextView mRedPurseFlagTextView;
	private View mInvoiceDivider;
	private TextView mIsInvoiceTextView;
	private ViewGroup paypalLayout;
	private ViewGroup creditCardLayout;
	private ViewGroup balanceLayout;
	private TextView mPaymentMoneyTempTextView;
	private TextView mRedPurseRightTextView;
	private ViewGroup redPurseLayout;

	private RatePlanInfo mRatePlanInfo;
	private HotelDocs mHotelDocs;
	private String mBouns;
	private String mTotalbouns;
	private String mPhoneString;
	private ArrayList<String> mLiveNameArrayList;
	private String mCurrentRoomAmount;
	private String mLatestarrival;
	private String mShowLatestarrival;
	private boolean mIsTimeGuarantee = false;
	private boolean mIsAmountGuarantee = false;
	private String mTotalPrice;
	/** 用来显示总钱数 */
	private float mShowTotalPrice;
	private MemberManaged mMemberManaged;
	private AlipayResult mAlipayResult;
	
	private Bundle mSavedInstanceState;

	// /**红包id*/
	// private String ticketid = "0";
	// /**红包价钱*/
	// private String ticketcash = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_payment);
		mSavedInstanceState = savedInstanceState;
		init();
	}

	@Override
	protected void init() {
		if(null == mSavedInstanceState){
		mRatePlanInfo = (RatePlanInfo) getIntent().getSerializableExtra(
				"RatePlanInfo");
		mHotelDocs = (HotelDocs) getIntent().getSerializableExtra("HotelDocs");
		mTotalPrice = getIntent().getStringExtra("totalprice");
		mBouns = getIntent().getStringExtra("bouns");
		mTotalbouns = getIntent().getStringExtra("totalbouns");
		mPhoneString = getIntent().getStringExtra("phoneString");
		mLiveNameArrayList = getIntent().getStringArrayListExtra(
				"liveNameArrayList");
		mCurrentRoomAmount = getIntent().getStringExtra("currentRoomAmoount");
		mLatestarrival = getIntent().getStringExtra("latestarrival");
		mShowLatestarrival = getIntent().getStringExtra("showLatestarrival");
		mIsTimeGuarantee = getIntent()
				.getBooleanExtra("IsTimeGuarantee", false);
		mIsAmountGuarantee = getIntent().getBooleanExtra("IsAmountGuarantee",
				false);
		
		}else {
			mRatePlanInfo = (RatePlanInfo) mSavedInstanceState.getSerializable("rateplaninfo");
			mHotelDocs = (HotelDocs) mSavedInstanceState.getSerializable("hoteldocs");
			mBouns = mSavedInstanceState.getString("bouns");
			mTotalbouns = mSavedInstanceState.getString("totalbouns");
			mPhoneString = 	mSavedInstanceState.getString("phonestring");
			mLiveNameArrayList = mSavedInstanceState.getStringArrayList("livenamearraylist");
			mCurrentRoomAmount = mSavedInstanceState.getString("currentroomamount");
			mLatestarrival = mSavedInstanceState.getString("latestarrival");
			mShowLatestarrival = mSavedInstanceState.getString("showlatestrarrival");
			mIsTimeGuarantee = mSavedInstanceState.getBoolean("istimeguarantee");
			mIsAmountGuarantee = mSavedInstanceState.getBoolean("isamountguarantee");
			mTotalPrice = mSavedInstanceState.getString("totalprice");
			mShowTotalPrice = mSavedInstanceState.getFloat("showtotalprice");
		}
		
		try {
			mShowTotalPrice = Float.parseFloat(mTotalPrice);
		} catch (Exception e) {
		}

		TextView guaranteesConditionTextView = (TextView) findViewById(R.id.guaranteesConditionTextView);
		if (!"".equals(mRatePlanInfo.PrepayRuleIds)
				&& mRatePlanInfo.PrepayRules.size() > 0) {
			PrepayRuleInfo prepayRuleInfo = mRatePlanInfo.PrepayRules.get(0);
			guaranteesConditionTextView.setText(prepayRuleInfo.Description);
			guaranteesConditionTextView.setVisibility(View.VISIBLE);
		} else {
			guaranteesConditionTextView.setVisibility(View.GONE);
		}
		TextView paymentMoneyTextView = (TextView) findViewById(R.id.paymentMoneyTextView);
		setTotalPriceFloatView(paymentMoneyTextView);

		mPaymentMoneyTempTextView = (TextView) findViewById(R.id.paymentMoneyTempTextView);
		int totalPrice = 0;
		try {
			totalPrice = (int) Float.parseFloat(mTotalPrice);
		} catch (Exception e) {
		}
		mPaymentMoneyTempTextView.setText("￥" + totalPrice);

		paypalLayout = (ViewGroup) findViewById(R.id.paypalLayout);
		creditCardLayout = (ViewGroup) findViewById(R.id.creditCardLayout);
		balanceLayout = (ViewGroup) findViewById(R.id.balanceLayout);

		mRedPurseFlagTextView = (TextView) findViewById(R.id.redPurseFlagTextView);
		mRedPurseTextView = (TextView) findViewById(R.id.redPurseTextView);
		mBalanceFlagTextView = (TextView) findViewById(R.id.balanceFlagTextView);
		mBalanceTextView = (TextView) findViewById(R.id.balanceTextView);
		mBalanceTextView.setText("0.00元");
		mBalanceRightTextView = (TextView) findViewById(R.id.balanceRightTextView);
		mBalanceRightTextView.setEnabled(false);
		balanceLayout.setEnabled(false);

		mInvoiceTitleEditTextClearView = (EditTextClearView) findViewById(R.id.invoiceTitleEditTextClearView);
		mInvoiceTitleEditTextClearView.getEditText().setHint("输入发票抬头");
		mInvoiceTitleEditTextClearView.getEditText().setText(
				SaveUserOperate.getInvoiceTitle(mContext));

		mNameEditTextClearView = (EditTextClearView) findViewById(R.id.nameEditTextClearView);
		String nameString = SaveUserOperate.getRecipients(mContext);
		if (TextUtils.isEmpty(nameString)) {
			nameString = SaveUserOperate.getLiveName(mContext);
		}
		mNameEditTextClearView.getEditText().setText(nameString);
		mNameEditTextClearView.getEditText().setHint("请输入收件人姓名");

		mInvoiceTypeTextView = (TextView) findViewById(R.id.invoiceTypeTextView);
		mInvoiceTypeTextView.setText(mApplication.mInvoiceTypeList.get(0));

		mPhoneEditTextClearView = (EditTextClearView) findViewById(R.id.phoneEditTextClearView);
		String phoneString = SaveUserOperate.getRecipientsPhone(mContext);
		if (TextUtils.isEmpty(phoneString)) {
			phoneString = SaveUserOperate.getLoginPhone(mContext);
		}
		mPhoneEditTextClearView.getEditText().setText(phoneString);
		mPhoneEditTextClearView.getEditText().setHint("固定电话或手机");

		mAddressEditTextClearView = (EditTextClearView) findViewById(R.id.addressEditTextClearView);
		mAddressEditTextClearView.getEditText().setHint("输入邮寄地址");
		mAddressEditTextClearView.getEditText().setText(
				SaveUserOperate.getMailAddress(mContext));
		mInvoiceLayout = (ViewGroup) findViewById(R.id.invoiceLayout);
		mInvoiceDivider = (ViewGroup) findViewById(R.id.invoiceDivider);
		mInvoiceDivider.setVisibility(View.VISIBLE);
		mInvoiceLayout.setVisibility(View.GONE);

		mRedPurseRightTextView = (TextView) findViewById(R.id.redPurseRightTextView);

		setListener();

		setTitleNavBar();

		memberGetManaged();
	}

	private void setTotalPriceFloatView(TextView textView) {

		float totalPrice = 0.0F;
		try {
			totalPrice = Float.parseFloat(mTotalPrice);

			BigDecimal bd = new BigDecimal(totalPrice);
			bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

			String moneyString = "";
			if (bd.floatValue() % 1.0 == 0) {
				// textView.setText("￥" + (int) (bd.floatValue()));
				moneyString = "￥" + (int) (bd.floatValue());
			} else {
				// textView.setText("￥" + bd.floatValue());
				moneyString = "￥" + (bd.floatValue());
			}

			SpannableStringBuilder moneySpannable = new SpannableStringBuilder(
					moneyString);
			moneySpannable.setSpan(new ForegroundColorSpan(mContext
					.getResources().getColor(R.color.list_gray_text_color)), 0,
					1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			float moneySize = mContext.getResources().getDimension(
					R.dimen.list_text_small_size);
			moneySpannable.setSpan(new AbsoluteSizeSpan((int) moneySize), 0, 1,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			textView.setText(moneySpannable);

		} catch (Exception e) {
		}
	}

	@Override
	protected void setListener() {
		balanceLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mBalanceRightTextView.setSelected(!mBalanceRightTextView
						.isSelected());
				selectedUscore(mBalanceRightTextView.isSelected());
			}
		});
		redPurseLayout = (ViewGroup) findViewById(R.id.redPurseLayout);
		redPurseLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mRedPurseRightTextView.setSelected(!mRedPurseRightTextView
						.isSelected());
				selectedRedPurse(mRedPurseRightTextView.isSelected());

			}
		});

		ViewGroup invoiceTypeModifyLayout = (ViewGroup) findViewById(R.id.invoiceTypeModifyLayout);
		invoiceTypeModifyLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, InvoiceTypeActivity.class);
				startActivityForResult(intent, 0);
			}
		});
		Button paymentButton = (Button) findViewById(R.id.paymentButton);
		paymentButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 确认支付
				payment();
			}
		});

		ViewGroup isInvoiceLayout = (ViewGroup) findViewById(R.id.isInvoiceLayout);
		isInvoiceLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mIsInvoiceTextView.setSelected(!mIsInvoiceTextView.isSelected());
				if (View.GONE == mInvoiceLayout.getVisibility()) {
					mInvoiceLayout.setVisibility(View.VISIBLE);
					mInvoiceDivider.setVisibility(View.GONE);
				} else if (View.VISIBLE == mInvoiceLayout.getVisibility()) {
					mInvoiceLayout.setVisibility(View.GONE);
					mInvoiceDivider.setVisibility(View.VISIBLE);
				}
			}
		});

		mIsInvoiceTextView = (TextView) findViewById(R.id.isInvoiceTextView);

		paypalLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mPaypalRightTextView.isSelected()) {
					mPaypalRightTextView.setSelected(!mPaypalRightTextView
							.isSelected());
					mCreditCardTextView.setSelected(!mPaypalRightTextView
							.isSelected());
				}
			}
		});

		creditCardLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mCreditCardTextView.isSelected()) {
					mCreditCardTextView.setSelected(!mCreditCardTextView
							.isSelected());
					mPaypalRightTextView.setSelected(!mCreditCardTextView
							.isSelected());
				}
			}
		});

		mPaypalRightTextView = (TextView) findViewById(R.id.paypalRightTextView);
		mCreditCardTextView = (TextView) findViewById(R.id.creditCardTextView);
	}

	/**
	 * 使用现金账户
	 * 
	 * @param selected
	 *            true标示使用现金账户，false标示没有使用现金账户
	 */
	private void selectedUscore(boolean selected) {
		int money = 0;
		try {
			money = Integer.parseInt(mMemberManaged.uscore);
		} catch (Exception e) {
		}
		if (selected) {

			if (money > 0) {
				mShowTotalPrice = mShowTotalPrice - money;
				if (mShowTotalPrice <= 0) {
					mPaymentMoneyTempTextView.setText("￥" + 0);
					mPaypalRightTextView.setEnabled(false);
					mCreditCardTextView.setEnabled(false);
					mPaypalRightTextView.setSelected(false);
					mCreditCardTextView.setSelected(false);
					paypalLayout.setEnabled(false);
					creditCardLayout.setEnabled(false);
				} else {
					mPaymentMoneyTempTextView.setText("￥"
							+ (ToolUtils.intByString(mShowTotalPrice + "")));
				}
			}
			mBalanceFlagTextView.setText("使用账户余额抵扣 : ");

		} else {

			mShowTotalPrice = mShowTotalPrice + money;

			mPaypalRightTextView.setEnabled(true);
			mCreditCardTextView.setEnabled(true);
			paypalLayout.setEnabled(true);
			creditCardLayout.setEnabled(true);
			mPaypalRightTextView.setSelected(false);
			mCreditCardTextView.setSelected(false);
			mBalanceFlagTextView.setText("可用账户余额 : ");
			mPaymentMoneyTempTextView.setText("￥"
					+ ToolUtils.intByString(mShowTotalPrice + ""));
		}
		
		updateUscoreShow();
	}

	/**
	 * 使用红包
	 * 
	 * @param selected
	 *            true使用红包，。false不使用红包
	 */
	private void selectedRedPurse(boolean selected) {

		int tempticketcash = 0;
		try {
			tempticketcash = Integer.parseInt(mMemberManaged.ticketcash);
		} catch (Exception e) {
		}
		if (selected) {

			if (tempticketcash > 0) {
				mShowTotalPrice = mShowTotalPrice - tempticketcash;
				if (mShowTotalPrice <= 0) {
					mPaymentMoneyTempTextView.setText("￥" + 0);
					mPaypalRightTextView.setEnabled(false);
					mCreditCardTextView.setEnabled(false);
					mPaypalRightTextView.setSelected(false);
					mCreditCardTextView.setSelected(false);
					paypalLayout.setEnabled(false);
					creditCardLayout.setEnabled(false);
				} else {
					mPaymentMoneyTempTextView.setText("￥"
							+ (ToolUtils.intByString(mShowTotalPrice + "")));
				}
			}
			mRedPurseFlagTextView.setText("使用红包 : ");
		} else {

			mShowTotalPrice = mShowTotalPrice + tempticketcash;

			mPaypalRightTextView.setEnabled(true);
			mCreditCardTextView.setEnabled(true);
			paypalLayout.setEnabled(true);
			creditCardLayout.setEnabled(true);
			mPaypalRightTextView.setSelected(false);
			mCreditCardTextView.setSelected(false);
			mRedPurseFlagTextView.setText("可用红包 : ");
			if (mShowTotalPrice <= 0) {
				mPaymentMoneyTempTextView.setText("￥" + (0));
			} else {
				mPaymentMoneyTempTextView.setText("￥"
						+ (ToolUtils.intByString(mShowTotalPrice + "")));
			}
		}

		updateUscoreShow();
	}

	@Override
	protected void setTitleNavBar() {
		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage("选择支付方式");
		titleNavBarView.setLeftDrawableImage(R.drawable.btn_title_back);
		titleNavBarView.setLeftButtonImageString(0, "返回", R.color.text_blue);
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				quit();
			}
		});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	private void memberGetManaged() {
		NetworkClient.getNetworkClient().PostRequest(
				new MemberGetManagedRequest(mContext),
				new MemberGetManagedResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								int money = 0;
								int ticketcash = 0;
								try {
									money = Integer
											.parseInt(memberManaged.uscore);
									
								} catch (Exception e) {
								}
								try {
									ticketcash = (int) Float
											.parseFloat(memberManaged.ticketcash);									
								} catch (Exception e) {
								}
								mMemberManaged = memberManaged;
								View userMoneyDivider = findViewById(R.id.userMoneyDivider);
								ViewGroup userMoneyLayout =(ViewGroup) findViewById(R.id.userMoneyLayout);
								if (ticketcash > 0) {
									mRedPurseTextView.setText(ticketcash + "元");
									redPurseLayout.setEnabled(true);
									mRedPurseRightTextView.setSelected(true);
									selectedRedPurse(true);
								} else {
									redPurseLayout.setEnabled(false);
									mRedPurseTextView.setText("0.00元");
									userMoneyDivider.setVisibility(View.GONE);
									redPurseLayout.setVisibility(View.GONE);
									
								}
								if (money > 0) {
									mBalanceTextView.setText(money + "元");
									mBalanceRightTextView.setEnabled(true);
									balanceLayout.setEnabled(true);
									mBalanceRightTextView.setSelected(true);
									selectedUscore(true);
								} else {
									mBalanceRightTextView.setEnabled(false);
									mBalanceTextView.setText("0.00元");
									balanceLayout.setEnabled(false);
									userMoneyDivider.setVisibility(View.GONE);
									balanceLayout.setVisibility(View.GONE);
								}
								
								if(ticketcash <=0 && money <= 0){
									userMoneyLayout.setVisibility(View.GONE);
								}
								
								updateUscoreShow();
							}
						});
					}

				});
	}

	/**
	 * 更新显示
	 */
	private void updateUscoreShow() {
		int uscore = 0;
		int ticketcash = 0;
		int totalPrice = 0;
		try {
			uscore = Integer.parseInt(mMemberManaged.uscore);
			ticketcash = (int) Float.parseFloat(mMemberManaged.ticketcash);
			totalPrice = ToolUtils.intByString(mTotalPrice);
		} catch (Exception e) {
		}

		if (0 == uscore) {
			return;
		}
		
		if (uscore >= totalPrice) {
			uscore = totalPrice;

			if (ticketcash > 0) {
				if (mRedPurseRightTextView.isSelected()) {
					// 选中红包
					if (ticketcash <= uscore) {
						uscore -= ticketcash;
					} else {
						uscore = 0;
					}
				} else {
					// 不选红包
				}
			}
		}else if(uscore < totalPrice){
			if(uscore + ticketcash >= totalPrice){
				if (mRedPurseRightTextView.isSelected()) {
					// 选中红包
					if(totalPrice >= ticketcash){
						uscore = totalPrice-ticketcash;
					}else {
						uscore = 0;
					}
				} else {
					// 不选红包
					
				}
			}else {
				
			}
		}
		
		mBalanceTextView.setText(uscore + "元");
		mRedPurseTextView.setText(ticketcash + "元");
		
		ViewGroup selectDefrayLayout = (ViewGroup)findViewById(R.id.selectDefrayLayout);
		if(mShowTotalPrice <= 0){
			selectDefrayLayout.setVisibility(View.GONE);
			mPaypalRightTextView.setEnabled(false);
			mCreditCardTextView.setEnabled(false);
		}else {
			selectDefrayLayout.setVisibility(View.VISIBLE);
			mPaypalRightTextView.setEnabled(true);
			mCreditCardTextView.setEnabled(true);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 发票类型返回
			switch (resultCode) {
			case RESULT_OK: {
				String invoiceTypeString = data.getStringExtra("InvoiceType");
				mInvoiceTypeTextView.setText(invoiceTypeString);
				break;
			}
			case RESULT_CANCELED: {

				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 保存状态
	 */
	private void saveSubmitInfo() {
		SaveUserOperate.setRecipientsPhone(mContext, mPhoneEditTextClearView
				.getEditText().getText().toString());
		SaveUserOperate.setRecipients(mContext, mNameEditTextClearView
				.getEditText().getText().toString());
		SaveUserOperate.setMailAddress(mContext, mAddressEditTextClearView
				.getEditText().getText().toString());
		SaveUserOperate.setInvoiceTitle(mContext,
				mInvoiceTitleEditTextClearView.getEditText().getText()
						.toString());
	}

	private void payment() {
		StringBuilder stringBuilder = new StringBuilder();
		if (!checkSubmitInfo(stringBuilder)) {

			HandlerToastUI
					.getHandlerToastUI(mContext, stringBuilder.toString());

		} else if ((mBalanceRightTextView.isSelected()|| mRedPurseRightTextView.isSelected())
				&& !mCreditCardTextView.isEnabled()
				&& !mPaypalRightTextView.isEnabled()) {

			createOrders("");

		} else if (mCreditCardTextView.isSelected()) {

			// 保存状态
			saveSubmitInfo();

			Intent intent = new Intent(mContext, CreditGuaranteesActivity.class);
			if (mRedPurseRightTextView.isSelected()) {
				intent.putExtra("ticketid", mMemberManaged.ticketid);
				intent.putExtra("ticketcash", mMemberManaged.ticketcash);
			}
			intent.putExtra("RatePlanInfo", mRatePlanInfo);
			intent.putExtra("HotelDocs", mHotelDocs);
			intent.putExtra("totalprice", mTotalPrice);
			intent.putExtra("bouns", mBouns);
			intent.putExtra("totalbouns", mTotalbouns);
			intent.putExtra("phoneString", mPhoneString);
			intent.putStringArrayListExtra("liveNameArrayList",
					mLiveNameArrayList);
			intent.putExtra("currentRoomAmoount", mCurrentRoomAmount);
			intent.putExtra("latestarrival", mLatestarrival);
			intent.putExtra("showLatestarrival", mShowLatestarrival);
			intent.putExtra("IsTimeGuarantee", mIsTimeGuarantee);
			intent.putExtra("IsAmountGuarantee", mIsAmountGuarantee);
			intent.putExtra("title", "信用卡预付");
			intent.putExtra("tips", "支付金额");
			// 发票
			String needinvoice = "0";
			if (View.GONE == mInvoiceLayout.getVisibility()) {
				// 不需要发票
				needinvoice = "0";
			} else if (View.VISIBLE == mInvoiceLayout.getVisibility()) {
				// 需要发票
				needinvoice = "1";
			}
			intent.putExtra("needinvoice", needinvoice);
			intent.putExtra("invoicetitle", mInvoiceTitleEditTextClearView
					.getEditText().getText().toString());
			intent.putExtra("invoicetype", mInvoiceTypeTextView.getText());
			// intent.putExtra("province = "";
			// intent.putExtra("city = "";
			// intent.putExtra("area = "";
			intent.putExtra("invoiceaddress", mAddressEditTextClearView
					.getEditText().getText().toString());
			intent.putExtra("invoicename", mNameEditTextClearView.getEditText()
					.getText().toString());
			intent.putExtra("invoicemobile", mPhoneEditTextClearView
					.getEditText().getText().toString());
			if (mBalanceRightTextView.isSelected() && null != mMemberManaged) {
				intent.putExtra("userscore", mMemberManaged.uscore);
			}

			startActivity(intent);
		} else if (mPaypalRightTextView.isSelected()) {

			// 保存状态
			saveSubmitInfo();

			createOrders(PAYMENTMOTHD_WEB);

		} else {
			HandlerToastUI.getHandlerToastUI(mContext, "请选择支付方式");
		}
	}

	private String requestParamEncode(String requestParam) {
		StringBuilder paramStringBuilder = new StringBuilder();
		try {
			String sign = "sign";
			String signType = "sign_type";
			String notify_url = "notify_url";
			String[] params = requestParam.split("&");
			for (String param : params) {

				String[] keyValue = param.split("=");
				String valueString = keyValue[1];
				// if (keyValue[0].equals(sign) || keyValue[0].equals(signType))
				// {
				// valueString = keyValue[1];
				// } else
				if (keyValue[0].equals(notify_url)) {
					String tempUrl = keyValue[1];
					tempUrl = tempUrl.substring(1, tempUrl.length() - 1);
					String tempStartUrl = keyValue[1].substring(0, 1);
					String tempEndUrl = keyValue[1].substring(
							keyValue[1].length() - 1, keyValue[1].length());
					tempStartUrl = URLEncoder.encode(tempStartUrl, "UTF-8");
					tempEndUrl = URLEncoder.encode(tempEndUrl, "UTF-8");
					// tempUrl = tempStartUrl + tempUrl + tempEndUrl;
					tempUrl = "\"" + URLEncoder.encode(tempUrl, "UTF-8") + "\"";
					valueString = tempUrl;

				}
				// else {
				// valueString = URLEncoder.encode(keyValue[1], "UTF-8");
				// }
				paramStringBuilder.append(keyValue[0]).append("=")
						.append(valueString).append("&");

			}
			paramStringBuilder.delete(paramStringBuilder.length() - 1,
					paramStringBuilder.length());
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		return paramStringBuilder.toString();
	}

	/**
	 * 调用支付宝客户端
	 */
	// private void callAppPayment(AlipayResult alipayResult) {
	// String redrecturl = alipayResult.redrecturl;
	// // final String paramString = requestParamEncode(redrecturl);
	// final String paramString =
	// "partner=\"2088001966153085\"&seller=\"2088001966153085\"&out_trade_no=\"6880997\"&subject=\"chailvtong\"&body=\"chailvtong\"&total_fee=\"0.01\"&notify_url=\"http://agent.gaia.elong.com/Payment.ExternalInterface/AlipaySecurityPayReceived.aspx\"&sign=\"sAdX%2b%2fYImO1l7KJabHgIxTW5qLM4Lerf8XOLwu7dlcSxK3QTppR8IF%2bMObpSMJShXYaPeKvjnk2bs2%2bJW6emlfhw1KqM1VjOlnz7xy7UolIQ4PUKfFMPVMGLmhJMqtbtGSRWzHt4fX8wj4SRGpK%2fVHNIMHYYghU7GuowAasu8iA%3d\"&sign_type=\"RSA\"";
	// // 获取订单组装字符串
	// new Thread() {
	// public void run() {
	// // PayHelper payHelper = new PayHelper((Activity)mContext);
	// // String result = payHelper.pay4Client(paramString);
	// // String result = payHelper.pay4Msp(paramString);
	// // 获取Alipay对象，构造参数为当前Activity和Handler实例对象
	// AliPay alipay = new AliPay((Activity) mContext, mHandler);
	// // 调用pay方法，将订单信息传入
	// String result = alipay.pay(paramString);
	// // 处理返回结果
	// }
	// }.start();
	//
	// }

	/**
	 * 调用网页支付网页
	 */
	private void callWebPayment(AlipayResult alipayResult) {

		String redrecturl = alipayResult.redrecturl;
		try {
			String req_data = "req_data=";
			String sec_id = "&sec_id=";
			int req_data_start_index = redrecturl.indexOf(req_data);
			int sec_id_index = redrecturl.indexOf(sec_id);
			String temp_req_data = redrecturl.substring(req_data_start_index
					+ req_data.length(), sec_id_index);
			String temp_req_data_encode = URLEncoder.encode(temp_req_data,
					"UTF-8");
			redrecturl = redrecturl
					.replace(temp_req_data, temp_req_data_encode);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// AppJump.goBrowser(mContext, redrecturl);
		
		//使用支付宝网页版支付
		MobclickAgent.onEvent(mContext,"Web_Payment");
		
		Intent intent = new Intent(mContext, PaypalWebViewActivity.class);
		intent.putExtra("title", "支付宝付款");
		intent.putExtra("url", redrecturl);
		intent.putExtra("returnurl", alipayResult.returnurl);
		startActivity(intent);
	}

	/**
	 * @param paymentmothd
	 *            调用支付宝Web：PAYMENTMOTHD_WEB（目前只支持web）；
	 *            调用支付宝客户端：PAYMENTMOTHD_APP； "" 标示现金账户够支付房费的，不需要信用卡或者支付宝
	 */
	private void createOrders(final String paymentmothd) {
		String starttime = "";
		String endtime = "";
		if (!"".equals(mRatePlanInfo.GuaranteeRuleIds)
				&& mRatePlanInfo.GuaranteeRules.size() > 0) {
			GuaranteeRuleInfo info = mRatePlanInfo.GuaranteeRules.get(0);
			starttime = info.StartTime;
			endtime = info.EndTime;
		}
		float totalprice = 0;
		try {
			totalprice = (Float.parseFloat(mRatePlanInfo.TotalRate) * Float
					.parseFloat(mCurrentRoomAmount));
		} catch (Exception e) {
		}
		String startdate = mApplication.mHotelSearchCondition.getStartDate();
		String enddate = mApplication.mHotelSearchCondition.getEndDate();
		String earlyarrival = "";
		StringBuilder customer = new StringBuilder();
		List<String> liveNameList = mLiveNameArrayList;
		for (int i = 0; i < liveNameList.size(); i++) {
			customer.append(liveNameList.get(i)).append(",");
		}
		customer.delete(customer.length() - 1, customer.length());
		String paymentType = ""; // Prepay","Selfpay"
		if (mRatePlanInfo.PaymentType.equalsIgnoreCase("PrePay")) {
			paymentType = "Prepay";
		} else if (mRatePlanInfo.PaymentType.equalsIgnoreCase("SelfPay")) {
			paymentType = "Selfpay";
		}

		// 不是预付，也不需要担保直接就可以提交
		String needcreditcard = "";
		String crednum = "";
		String cvv = "";
		String expyear = "";
		String expmonth = "";
		String holdername = "";
		String idtype = "";
		String idno = "";

		// 发票
		String needinvoice = "0";
		String invoicetitle = "";
		String invoicetype = "";
		String province = "";
		String city = "";
		String area = "";
		String invoiceaddress = "";
		String invoicename = "";
		String invoicemobile = "";
		String userscore = "";
		if (mBalanceRightTextView.isSelected() && null != mMemberManaged) {
			userscore = mMemberManaged.uscore;
		}
		if (("".equals(paymentmothd) || paymentmothd.equals(PAYMENTMOTHD_WEB))
				&& mIsInvoiceTextView.isSelected()) {
			if (View.GONE == mInvoiceLayout.getVisibility()) {
				// 不需要发票
				needinvoice = "0";
			} else if (View.VISIBLE == mInvoiceLayout.getVisibility()) {
				// 需要发票
				needinvoice = "1";
			}
			invoicetitle = mInvoiceTitleEditTextClearView.getEditText()
					.getText().toString();
			invoicetype = mInvoiceTypeTextView.getText().toString();
			invoiceaddress = mAddressEditTextClearView.getEditText().getText()
					.toString();
			invoicename = mNameEditTextClearView.getEditText().getText()
					.toString();
			invoicemobile = mPhoneEditTextClearView.getEditText().getText()
					.toString();

		}

		String bouns = Integer.parseInt(mRatePlanInfo.Bonus) + "";
		String totalbouns = Integer.parseInt(mRatePlanInfo.Bonus)
				* Integer.parseInt(mCurrentRoomAmount) + "";
		// final String paymentmothd = PAYMENTMOTHD_WEB;
		// final String paymentmothd = PAYMENTMOTHD_APP;
		String paymentmothds = "";

		String guaranteeType = "";
		boolean guarantee = false;
		if ((!TextUtils.isEmpty(mRatePlanInfo.GuaranteeRuleIds) && mRatePlanInfo.GuaranteeRules
				.size() > 0)) {
			GuaranteeRuleInfo guaranteeRuleInfo = mRatePlanInfo.GuaranteeRules
					.get(0);
			int amount = 100;
			int currentAmount = 0;
			try {
				amount = ToolUtils.intByString(guaranteeRuleInfo.Amount);
				currentAmount = ToolUtils.intByString(mCurrentRoomAmount);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!mIsAmountGuarantee && !mIsTimeGuarantee) {
				guarantee = true;
			} else {
				// if (mLatestarrival.contains("担保")
				if (mShowLatestarrival.contains("担保")
						|| (mIsAmountGuarantee && currentAmount >= amount)) {
					guarantee = true;
				}
			}
		}
		if (guarantee) {
			guaranteeType = (!mIsAmountGuarantee && !mIsTimeGuarantee) ? "2"
					: "1";
		} else {
			guaranteeType = "0";
		}
		String ticketid = "0";
		String ticketcash = "0";
		if (mRedPurseRightTextView.isSelected()) {
			ticketid = mMemberManaged.ticketid;
			ticketcash = mMemberManaged.ticketcash;
		}
		NetworkClient.getNetworkClient().PostRequest(
				new CreateOrderRequest(mContext, mHotelDocs.hotelId,
						mRatePlanInfo.RoomTypeId, mRatePlanInfo.RateId,
						mHotelDocs.hotelName, mRatePlanInfo.RoomName,
						mRatePlanInfo.RateName, starttime, endtime,
						mCurrentRoomAmount + "", mRatePlanInfo.CustomerType,
						paymentType, totalprice + "", startdate, enddate,
						earlyarrival, mLatestarrival, customer.toString(),
						mPhoneString, needcreditcard, crednum, cvv, expyear,
						expmonth, holdername, idtype, idno, needinvoice,
						invoicetitle, invoicetype, province, city, area,
						invoiceaddress, invoicename, invoicemobile, userscore,
						bouns, totalbouns, paymentmothd, paymentmothds,
						guaranteeType, ticketid, ticketcash),
				new CreateOrderResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						if (1 == status) {
							mAlipayResult = alipayResult;

							if (paymentmothd.equals(PAYMENTMOTHD_WEB)) {
								callWebPayment(mAlipayResult);
								finish();
							} else if (paymentmothd.equals(PAYMENTMOTHD_APP)) {
								// callAppPayment(mAlipayResult);
							} else if (paymentmothd.equals("")) {
								// 完全使用账户余额和红包定酒店成功
								HandlerPostUI.getHandlerPostUI(new Runnable() {

									@Override
									public void run() {
										//完全使用账户余额和红包订酒店
										MobclickAgent.onEvent(mContext,"Account_Balance_Reward");
										showDialog();
									}
								});
							}

						} else if (0 == status) {
							HandlerToastUI.getHandlerToastUI(mContext,
									resultTextString);
						}
					}
				});

	}

	private void showDialog() {

		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("提交成功");
		customAlertDialog.setLeftButton("查看订单", new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext, OrdersActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		customAlertDialog.setCancelable(false);
		customAlertDialog.setCanceledOnTouchOutside(false);
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	private boolean checkSubmitInfo(StringBuilder stringBuilder) {
		stringBuilder.delete(0, stringBuilder.length());
		if ((!mCreditCardTextView.isSelected() && !mPaypalRightTextView
				.isSelected())
				&& !((mBalanceRightTextView.isSelected() || mRedPurseRightTextView.isSelected())
						&& !mCreditCardTextView.isEnabled() && !mPaypalRightTextView
							.isEnabled())) {
			stringBuilder.append("请选择支付方式");
			return false;
		} else if (mIsInvoiceTextView.isSelected()) {
			// 需要发票，开始验证
			if (TextUtils.isEmpty(mInvoiceTitleEditTextClearView.getEditText()
					.getText().toString())) {
				stringBuilder.append("请输入发票抬头");
				return false;
			} else if (TextUtils.isEmpty(mNameEditTextClearView.getEditText()
					.getText().toString())) {
				stringBuilder.append("请输入收件人姓名");
				return false;
			} else if (TextUtils.isEmpty(mPhoneEditTextClearView.getEditText()
					.getText().toString())) {
				stringBuilder.append("请输入联系方式");
				return false;
			} else if (TextUtils.isEmpty(mAddressEditTextClearView
					.getEditText().getText().toString())) {
				stringBuilder.append("输入邮寄地址");
				return false;
			}
		}
		return true;
	}

	private void quit() {

		saveSubmitInfo();

		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		outState.putSerializable("rateplaninfo", mRatePlanInfo);
		outState.putSerializable("hoteldocs", mHotelDocs);
		outState.putString("bouns", mBouns);
		outState.putString("totalbouns", mTotalbouns);
		outState.putString("phonestring", mPhoneString);
		outState.putStringArrayList("livenamearraylist", mLiveNameArrayList);
		outState.putString("currentroomamount", mCurrentRoomAmount);
		outState.putString("latestarrival", mLatestarrival);
		outState.putString("showlatestrarrival", mShowLatestarrival);
		outState.putBoolean("istimeguarantee", mIsTimeGuarantee);
		outState.putBoolean("isamountguarantee", mIsAmountGuarantee);
		outState.putString("totalprice", mTotalPrice);
		outState.putFloat("showtotalprice", mShowTotalPrice);
		
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if(null != savedInstanceState){
			mRatePlanInfo = (RatePlanInfo) savedInstanceState.getSerializable("rateplaninfo");
			mHotelDocs = (HotelDocs) savedInstanceState.getSerializable("hoteldocs");
			mBouns = savedInstanceState.getString("bouns");
			mTotalbouns = savedInstanceState.getString("totalbouns");
			mPhoneString = 	savedInstanceState.getString("phonestring");
			mLiveNameArrayList = savedInstanceState.getStringArrayList("livenamearraylist");
			mCurrentRoomAmount = savedInstanceState.getString("currentroomamount");
			mLatestarrival = savedInstanceState.getString("latestarrival");
			mShowLatestarrival = savedInstanceState.getString("showlatestrarrival");
			mIsTimeGuarantee = savedInstanceState.getBoolean("istimeguarantee");
			mIsAmountGuarantee = savedInstanceState.getBoolean("isamountguarantee");
			mTotalPrice = savedInstanceState.getString("totalprice");
			mShowTotalPrice = savedInstanceState.getFloat("showtotalprice");
		}
	}

}
